<template>
	<view class="content" :prop="domId" :change:prop="html2canvas.create" v-if="dataInfo.length > 0">
	
		<swiper class="poster_swiper" previous-margin="86rpx" circular :current="swiperIndex" next-margin="86rpx" @change="onSwiperChange">
			<swiper-item class="swiper-item" v-for="(item, index) of dataInfo" :key="index">
				<view :ref="swiperIndex == index ? 'html2canvas' : ''" class="goods_info_box" :class="`${swiperIndex == index ? 'active' : ''} goods_info_box${index}`" :id="swiperIndex == index ? domId : ''">
					<image class="goods_image" :src="$wanlshop.oss(dataInfo[index].media)" mode="widthFix"></image>
					<view class="goods_info" v-show="index == 0">
						<view class="title">我的邀请码</view>
						<view class="code">{{user.invite_code}}</view>
						<view class="username">{{user.nickname}}</view>
						<view class="contents">
							邀请你一起加入银龄大家庭，分享有趣生活，体验精彩社区
						</view>
						<canvas class="QRCodeSrc" canvas-id="QRCodeSrc0" />
						<view class="subtitle">扫码注册</view>
					</view>
					<view class="goods_info" v-show="index == 1">
						<view class="cu-avatar round"
							:style="{backgroundImage: 'url('+ $wanlshop.oss(user.avatar, 52, 52, 2, 'avatar') +')'}">
						</view>
						<view class="username">{{user.nickname}}</view>
						<view class="contents">
							邀请你一起加入银龄大家庭 <br>
							分享有趣生活，体验精彩社区
						</view>
						<view class="bottom">
							<view class="left">
								<view class="title">我的邀请码</view>
								<view class="code">
									<image
										:src="$wanlshop.oss('/uploads/20231027/3d1ca64d1ecd03455cab69adea0028a5.jpg')"
										mode="heightFix"></image>
									<text>{{user.invite_code}}</text>
								</view>
								<view class="subtitle">注册时填写邀请码，即可接受邀请</view>
							</view>
							<canvas class="QRCodeSrc" canvas-id="QRCodeSrc1" style="width: 120rpx;height: 120rpx;" />
						</view>
					</view>
					<view class="goods_info" v-show="index == 2">
						<view class="text">
							<view class="cu-avatar round"
								:style="{backgroundImage: 'url('+ $wanlshop.oss(user.avatar, 52, 52, 2, 'avatar') +')'}">
							</view>
							<view class="username">{{user.nickname}}</view>
							<text>{{user.invite_code}}</text>
							<view class="title">我的邀请码</view>
						</view>

						<view class="bottom">
							<canvas class="QRCodeSrc" canvas-id="QRCodeSrc2" style="width: 130rpx;height: 130rpx;" />
							<view class="subtitle">扫码注册</view>
						</view>
					</view>
				</view>
			</swiper-item>
		</swiper>

		<view class="page-foot">
			<view class="template-list">
				<view class="tips text-sm wanl-gray" @tap="save()">
					<text class="wlIcon-fuzhi margin-right-xs"></text>保存到相册
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import uQRCode from '@/common/uqrcode.js';
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				domId: '',
				swiperIndex: 0,
				filePath: '',
				QRCodeSrc0: '',
				QRCodeSrc1: '',
				QRCodeSrc2: '',
				dataInfo: []
			}
		},
		onLoad() {
			this.loadData()
			this.makeQRCode(180,'QRCodeSrc0')
			this.makeQRCode(120,'QRCodeSrc1')
			this.makeQRCode(130,'QRCodeSrc2')
		},
		// watch: {
		// 	swiperIndex(newValue, oldValue) {
		// 		switch (Number(newValue)){
		// 			case 0:
		// 				this.makeQRCode(180)
		// 				break;
		// 			case 1:
		// 				this.makeQRCode(120)
		// 				break;
		// 			case 2:
		// 				this.makeQRCode(130)
		// 				break;
		// 			default:
		// 				break;
		// 		}
		// 	}
		// },
		computed: {
			...mapState(['common', 'user']),
		},
		methods: {
			makeQRCode(s,key) {
				uQRCode.make({
					canvasId: key,
					text: `https://${this.$config.baseUrl}/weixin/pages/user/auth/name?type=2&invite_code=${this.user.invite_code}`,
					size: uni.upx2px(s),
					success: res => {
						this[key] = res;
					}
				});
			},
			/**
			 * param flag 是否是任意长度
			 * param min 任意长度最小值
			 * param max 任意长度最大值
			 */
			randomStr(flag, min, max) {
				var str = "";
				var index = "";
				var range = min;
				var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
					't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
					'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
				];
				//min,max范围内随机的一个数
				if (flag) {
					range = Math.floor(Math.random() * (max - min + 1) + min);
				}
				for (var i = 0; i < range; i++) {
					index = Math.round(Math.random() * (arr.length - 1));
					str += arr[index];
				}
				return str;
			},
			save() {
				console.log(1)
				this.domId = this.randomStr(true,4,8)
				// this.domId = `swiper${this.swiperIndex}`;
			},

			showLoading() {
				uni.showToast({
					title: "正在保存图片",
					icon: "none",
					mask: true,
					duration: 100000
				})
			},
			hideLoading() {
				uni.hideToast();
			},
			/**
			 * 渲染完毕接收图片
			 * @param {String} filePath
			 */
			async renderFinish(base64, k) {
				// #ifdef APP-PLUS
				this.saveBaseImgFile(base64)
				// #endif
				// #ifdef H5
				this.savePicture(base64)
				// #endif
			},
			async loadData(option) {
				await uni.request({
					url: '/publics/advert/content',
					method: 'post',
					data: {
						position: 'qrcode_banner'
					},
					success: res => {
						this.dataInfo = res.data
					}
				})
				// uni.request({
				// 	url: '/member/user/qrcode',
				// 	method: 'post',
				// 	success: res => {
				// 		this.QRCodeSrc = res.data.qrcode;
				// 	}
				// })
			},
			onSwiperChange(e) {
				this.swiperIndex = e.detail.current
			},
			// 将base64 图片保存到本地系统相册
			saveBaseImgFile(base64) {
				const bitmap = new plus.nativeObj.Bitmap('base64')
				bitmap.loadBase64Data(base64, () => {
						const url = '_doc/' + new Date().getTime() + '.png'
						bitmap.save(
							url, {
								overwrite: true // 是否覆盖
								// quality: 'quality'  // 图片清晰度
							},
							(i) => {
								uni.saveImageToPhotosAlbum({
									filePath: url,
									success: () => {
										this.$wanlshop.msg('图片保存成功')
										bitmap.clear()
									}
								})
							},
							(e) => {
								this.$wanlshop.msg('图片保存失败')
								bitmap.clear()
							}
						)
					},
					(e) => {
						this.$wanlshop.msg('图片保存失败')
						bitmap.clear()
					}
				)
			},
			savePicture(base64) {
				// var arr = base64.split(','); //可以这样去掉data:image/png;base64,只拿，号后面部分  
				var bytes = atob(base64)
				let ab = new ArrayBuffer(bytes.length);
				console.log(ab)
				let ia = new Uint8Array(ab);
				for (let i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i);
				}
				var blob = new Blob([ab], {
					type: 'application/octet-stream'
				});
				var url = URL.createObjectURL(blob);
				var a = document.createElement('a');
				a.href = url;
				a.download = new Date().valueOf() + ".jpg";
				var e = document.createEvent('MouseEvents');
				e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				a.dispatchEvent(e);
				URL.revokeObjectURL(url);
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		background: #f1f1f1;
	}

	.content {
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.page-foot {
		position: fixed;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 30;
		background-color: #e5e5e5;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.template-list .tips {
		position: absolute;
		display: flex;
		align-items: center;
		justify-items: center;
		justify-content: center;
		top: -60rpx;
		width: 100%;
	}

	.template-list .tips .wlIcon-31tishi {
		font-size: 32rpx;
	}


	.poster_swiper {
		// height: 940rpx;
		// width: 634rpx;
		width: 100%;
		height: 846rpx;
		.swiper-item {
			box-sizing: border-box;
			display: flex;
			align-items: center;
			height: 846rpx;
			width: 570rpx;

			.goods_info_box {
				height: 846rpx;
				width: 570rpx;
				transform: scale(0.88);
				transition: all 0.4s;
				position: relative;
				overflow: hidden;

				&.active {
					transform: scale(1);
				}

				.goods_image {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
				}

				.goods_info {
					width: 100%;
					position: relative;
					bottom: 0;
					z-index: 9;

					.title {}
				}
			}
		}
	}

	.goods_info_box0 .goods_info {
		width: 100%;
		height: 100%;

		.title {
			font-size: 34rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 400;
			color: #193920;
			line-height: 48rpx;
			text-align: center;
			padding-top: 72rpx;
			padding-bottom: 34rpx;
		}

		.code {
			font-size: 124rpx;
			font-family: DIN-Medium, DIN;
			font-weight: 500;
			color: #203D1E;
			text-align: center;
		}

		.username {
			height: 34rpx;
			font-size: 24rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 400;
			color: #492306;
			line-height: 34rpx;
			text-align: center;
			margin-bottom: 40rpx;
		}

		.contents {
			font-size: 28rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #666666;
			line-height: 33rpx;
			margin: 0 48rpx;
		}

		.QRCodeSrc {
			width: 180rpx;
			height: 180rpx;
			border-radius: 10rpx;
			position: absolute;
			bottom: 60rpx;
			left: 50%;
			margin-left: -90rpx;
		}

		.subtitle {
			position: absolute;
			bottom: 20rpx;
			width: 100%;
			height: 36rpx;
			font-size: 26rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #555555;
			line-height: 36rpx;
			text-align: center;
		}
	}

	.goods_info_box1 .goods_info {
		width: 100%;
		height: 100%;

		.cu-avatar {
			width: 108rpx;
			height: 108rpx;
			margin-top: 78rpx;
			margin-left: 92rpx;
		}

		.username {
			height: 50rpx;
			font-size: 36rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #1B5340;
			line-height: 50rpx;
			margin-left: 56rpx;
			margin-top: 16rpx;
		}

		.contents {
			font-size: 22rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #1B5340;
			line-height: 30rpx;
			margin-left: 56rpx;
			margin-top: 24rpx;
		}

		.bottom {
			position: absolute;
			bottom: 30rpx;
			width: 100%;
			display: flex;
			justify-content: space-between;
			padding: 0 30rpx;

			.left {
				.title {
					height: 30rpx;
					font-size: 22rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #777777;
					line-height: 30rpx;
					margin-bottom: 12rpx;
				}

				.code {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					margin-bottom: 10rpx;

					text {
						height: 56rpx;
						font-size: 46rpx;
						font-family: DIN-Medium, DIN;
						font-weight: 500;
						color: #333333;
						line-height: 56rpx;
						margin-left: 10rpx;
					}

					image {
						width: 36rpx;
						height: 36rpx;
					}
				}

				.subtitle {
					height: 28rpx;
					font-size: 20rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #777777;
					line-height: 28rpx;
				}
			}

			image {
				width: 120rpx;
				height: 120rpx;
			}
		}
	}

	.goods_info_box2 .goods_info {
		width: 100%;
		height: 100%;

		.text {
			position: absolute;
			bottom: 52rpx;
			left: 100rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.cu-avatar {
				width: 126rpx;
				height: 126rpx;
			}

			.username {
				font-size: 24rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #492306;
				line-height: 34rpx;
				padding-top: 14rpx;
				padding-bottom: 22rpx;
			}

			text {
				font-size: 38rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #333333;
				line-height: 54rpx;
			}

			.title {
				font-size: 24rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #8F8F8F;
				line-height: 34rpx;
				padding-top: 10rpx;
			}
		}

		.bottom {
			position: absolute;
			bottom: 38rpx;
			right: 50rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.subtitle {
				font-size: 24rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #6C6C6C;
				line-height: 34rpx;
			}

			image {
				width: 130rpx;
				height: 130rpx;
				margin-bottom: 10rpx;
			}
		}
	}
	
	.qrcode-canvas {
		position: fixed;
		right: 100vw;
		bottom: 100vh;
		z-index: -999;
	}
	
</style>

<script module="html2canvas" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		methods: {
			async create(domId, k) {
				if (!domId) return false;
				try {
					this.$ownerInstance.callMethod('showLoading', true);
					const timeout = setTimeout(async () => {
						const shareContent = document.querySelector('#' + domId);
						const canvas = await html2canvas(shareContent, {
							width: shareContent.offsetWidth, //设置canvas尺寸与所截图尺寸相同，防止白边
							height: shareContent.offsetHeight, //防止白边
							logging: true,
							useCORS: true
						});
						const base64 = canvas.toDataURL('image/jpeg', 1);
						this.$ownerInstance.callMethod('renderFinish', base64, k);
						this.$ownerInstance.callMethod('hideLoading', true);
						clearTimeout(timeout);
					}, 1500);
				} catch (error) {
					console.log(error)
				}
			}
		}
	}
</script>